//
//  NDCalculatorViewModel.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/11/4.
//

import SwiftUI

class NDCalculatorViewModel: ObservableObject {
    @Published var calculatorModel: CalculatorModel?
    @Published var isLoading = false
    @Published var errorMessage: String?
    
    @Published var calculateSuccess = false
    
    @Published var showResult = false
    @Published var principal: Int = 0

    // 用于显示的格式化字符串
    @Published var displayInterestAmount: String = ""
    @Published var displayTotalAmount: String = ""
    
    func requestCalculatorResult(loanAmount: Int,
                                 loanTerm: Int,
                                 rate: Float,
                                 type: LoanDurationType) {
        isLoading = true
        errorMessage = nil
        calculateSuccess = false
        
        NDRequestManager.requestCalculatorResult(loanAmount: loanAmount,
                                                 loanTerm: loanTerm,
                                                 rate: rate,
                                                 type: type) { [weak self] model, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.isLoading = false

                if let _ = error {
                    self.errorMessage = msg
                    return
                }
                
                guard let model = model else {
                    self.errorMessage = "failed"
                    return
                }
                
                self.calculatorModel = model
                self.calculateSuccess = true
                self.showResult = true
                if let tenaciistic = model.tenaciistic {
                    self.principal = Int(tenaciistic) ?? 0
                }
                
                // 处理原始数值
                let interestValue = Double(model.emstatementose ?? "") ?? 0.0
                let totalValue = Double(model.personal ?? 0)

                // 生成显示字符串（去除无效的零）
                self.displayInterestAmount = self.removeTrailingZeros(from: interestValue)
                self.displayTotalAmount = self.removeTrailingZeros(from: totalValue)
            }
        }
    }
    
    /// 去除小数点后无效的零
    private func removeTrailingZeros(from number: Double) -> String {
        guard number.isFinite else { return "0" }
        
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.minimumFractionDigits = 0
        formatter.maximumFractionDigits = 10  // 设置足够大的小数位数
        
        return formatter.string(from: NSNumber(value: number)) ?? "\(number)"
    }
}
